package com.rzico.sbl.ui.report_0537

import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.core.widget.NestedScrollView
import com.rzico.sbl.R
import com.rzico.sbl.databinding.FragmentHomeQfBinding
import com.rzico.sbl.model.ManagerContent
import com.rzico.sbl.other.userRole
import com.rzico.sbl.ui.report.driver.DriverStationActivity
import com.rzico.sbl.ui.report.other.goToOffice
import com.xinnuo.common.decoration.GridVerticalDecoration
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.dp2px
import com.xinnuo.common.helper.intValue
import com.xinnuo.common.view.FullyGridLayoutManager
import com.xinnuo.common_ui.base.NavigationFragment
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.common_ui.view.BadgeTextView
import com.xinnuo.slimadapter.SlimAdapter
import org.json.JSONObject

class QFHomeFragment : NavigationFragment() {

    private var mBinding: FragmentHomeQfBinding? = null
    private lateinit var mIconAdapter: SlimAdapter

    override fun getViewModel() = get<QFHomeViewModel>()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ) = FragmentHomeQfBinding
        .inflate(inflater, container, false)
        .also { mBinding = it }
        .root

    override fun initTitle() {
        initLayout()
        initListener()

        observeData()
    }

    private fun initLayout() {
        mBinding?.let { binding ->
            binding
                .homeIcons
                .apply {
                    itemAnimator = null
                    isNestedScrollingEnabled = false

                    layoutManager = FullyGridLayoutManager(getIContext(), 4)

                    addItemDecoration(GridVerticalDecoration(vertical = 15f))

                    mIconAdapter = SlimAdapter.creator()
                        .register<ManagerContent>(R.layout.item_home_icon) { jector, bean, _ ->

                            // 解构声明
                            val (title, imageId, id, _, count) = bean

                            jector.apply {
                                text(R.id.item_icon_title, title)
                                image(R.id.item_icon_img, imageId)

                                with<BadgeTextView>(R.id.item_icon_num) {
                                    it.setBadgeCount(count)
                                }

                                clicked {
                                    when (id) {
                                        "财务" -> startActivityEx<QFFinanceOrderActivity>()
                                        "办公室" -> goToOffice()
                                        "水站统计" -> startActivityEx<DriverStationActivity>()
                                    }
                                }
                            }
                        }
                        .attachTo(this)
                }
        }
    }

    /**
     * 设置点击事件
     */
    private fun initListener() {
        mBinding?.apply {
            // 滑动监听
            homeScroll.setOnScrollChangeListener(
                NestedScrollView.OnScrollChangeListener { _, _, scrollY, _, _ ->
                    // 变化高度范围，单位像素
                    val changeHeight = dp2px(102f)

                    // 当滑动距离 <= 指定高度的时候，改变背景的透明度，达到渐变的效果
                    if (scrollY in 0..changeHeight) {
                        // 计算透明度值
                        val alpha = scrollY.toFloat() / changeHeight
                        // 改变图片背景的透明度
                        homeImg.alpha = 1f - alpha
                        // 改变标题背景的透明度
                        homeBg.alpha = alpha
                    } else {
                        // 将图片背景设置为非透明状态
                        homeImg.alpha = 0f
                        // 将标题背景设置为透明状态
                        homeBg.alpha = 1f
                    }
                }
            )
        }
    }

    /**
     * livedata 数据监听
     */
    private fun observeData() {
        mBinding?.apply {
            getViewModel()
                .mNotice
                .observe(getLifecycleOwner()) { value ->
                    layout.homeNotice.text = value
                }

            getViewModel()
                .mMessageEvent
                .observe(getLifecycleOwner()) { value ->
                    layout.homeMsgHint.isVisible = value > 0
                }

            when (userRole) {
                // 财务
                "5" -> {
                    homeIcons.visible()    //图标
                    layout.homeScan.gone() //扫一扫

                    mList.addItems(getViewModel().financeIcons())
                    mIconAdapter.setDataList(mList)
                }
                // 办公室
                "11" -> {
                    homeIcons.visible()    //图标
                    layout.homeScan.gone() //扫一扫

                    mList.addItems(getViewModel().officeIcons())
                    mIconAdapter.setDataList(mList)
                }
            }

        }
    }

    /**
     * 首页数据获取
     */
    private fun getHomeData() {
        getViewModel().getNotice()    //刷新公告
        getViewModel().messageCount() //刷新消息

        getViewModel()
            .orderCount()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = {
                    val obj = JSONObject(it)

                    when (userRole) {
                        // 财务
                        "5" -> {
                            (mList[0] as ManagerContent)
                                .count = obj.optNotNull("unpaid").intValue

                            mIconAdapter.notifyItemChanged(0)
                        }
                        // 办公室
                        "11" -> {
                            (mList[0] as ManagerContent)
                                .count = obj.optNotNull("unshipped").intValue

                            mIconAdapter.notifyItemChanged(0)
                        }
                    }
                }
            )
    }

    override fun onStart() {
        super.onStart()
        getHomeData()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mBinding = null
    }

}